package com.platform.core.service.impl;


import com.google.common.base.Strings;
import com.platform.comm.repository.CustomBaseRepository;
import com.platform.comm.service.impl.CommonBizImpl;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.PathMetadata;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.PathBuilder;
import com.platform.comm.enums.YnEnum;
import com.platform.comm.exceptions.RestApiException;
import com.platform.core.service.BaseEntityBiz;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.MultiValueMap;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;

/**
 * @author libin
 */
public class BaseEntityBizImpl<R extends CustomBaseRepository<T, String>, T extends Serializable> extends CommonBizImpl<R, T, String> implements BaseEntityBiz<T> {

    public BaseEntityBizImpl(R baseRepository) {
        super(baseRepository);
    }

    @Transactional(rollbackFor = {RestApiException.class})
    @Override
    public void remove(String id) {
        batchRemove(Collections.singletonList(id));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void batchRemove(List<String> ids) {
        ids.forEach(this::remove);
    }

    protected BooleanBuilder builderConditions(Predicate predicate, MultiValueMap<String, String> parameters, Class<T> cls, PathMetadata pathMetadata) {
        PathBuilder<T> pathBuilder = new PathBuilder<>(cls, pathMetadata);
        final String delFlag = parameters.getFirst("delFlag");
        BooleanBuilder builder = new BooleanBuilder(predicate);
        if (Strings.isNullOrEmpty(delFlag) || delFlag.equals(YnEnum.N.name())) {
            builder.and(pathBuilder.get("delFlag").eq(YnEnum.N));
        }
        return builder;
    }
}
